/*
 * @Author: xiaopang
 * @Date: 2025-10-17 16:37:39
 * @LastEditTime: 2025-10-17 16:40:25
 * @LastEditors: xiaopang
 */
import axios from 'axios';
import { showToast, showLoadingToast, closeToast } from 'vant';
import { useUserStore } from '@/store/user';
import router from '@/router';

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL, // API基础路径
  timeout: 30000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    const userStore = useUserStore();

    // 如果token存在，添加到请求头
    if (userStore.token) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`;
    }

    // 如果需要显示loading
    if (config.loading !== false) {
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });
    }

    return config;
  },
  error => {
    console.error('请求错误：', error);
    closeToast();
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    closeToast();

    const res = response.data;

    // 根据实际后端返回的数据结构调整
    // 假设后端返回格式为 { code: 200, data: {}, message: '' }
    if (res.code === 200 || res.code === 0) {
      return res.data;
    }

    // 其他错误码处理
    showToast({
      message: res.message || '请求失败',
      position: 'top'
    });

    return Promise.reject(new Error(res.message || '请求失败'));
  },
  error => {
    closeToast();
    console.error('响应错误：', error);

    const { response } = error;

    if (response) {
      const userStore = useUserStore();

      switch (response.status) {
        case 400:
          showToast({
            message: response.data?.message || '请求参数错误',
            position: 'top'
          });
          break;
        case 401:
          showToast({
            message: '登录已过期，请重新登录',
            position: 'top',
            onClose: () => {
              userStore.logout();
              router.replace('/login');
            }
          });
          break;
        case 403:
          showToast({
            message: '没有权限访问',
            position: 'top'
          });
          break;
        case 404:
          showToast({
            message: '请求的资源不存在',
            position: 'top'
          });
          break;
        case 500:
          showToast({
            message: '服务器错误',
            position: 'top'
          });
          break;
        case 502:
          showToast({
            message: '网关错误',
            position: 'top'
          });
          break;
        case 503:
          showToast({
            message: '服务不可用',
            position: 'top'
          });
          break;
        default:
          showToast({
            message: response.data?.message || '请求失败',
            position: 'top'
          });
      }
    } else if (error.message.includes('timeout')) {
      showToast({
        message: '请求超时，请稍后重试',
        position: 'top'
      });
    } else if (error.message.includes('Network Error')) {
      showToast({
        message: '网络连接失败，请检查网络',
        position: 'top'
      });
    } else {
      showToast({
        message: '请求失败，请稍后重试',
        position: 'top'
      });
    }

    return Promise.reject(error);
  }
);

// 封装常用请求方法
export const request = {
  // GET请求
  get(url, params = {}, config = {}) {
    return service.get(url, { params, ...config });
  },

  // POST请求
  post(url, data = {}, config = {}) {
    return service.post(url, data, config);
  },

  // PUT请求
  put(url, data = {}, config = {}) {
    return service.put(url, data, config);
  },

  // DELETE请求
  delete(url, params = {}, config = {}) {
    return service.delete(url, { params, ...config });
  },

  // PATCH请求
  patch(url, data = {}, config = {}) {
    return service.patch(url, data, config);
  },

  // 文件上传
  upload(url, formData, config = {}) {
    return service.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      ...config
    });
  },

  // 下载文件
  download(url, params = {}, filename = '') {
    return service
      .get(url, {
        params,
        responseType: 'blob'
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename || '下载文件';
        link.click();
        window.URL.revokeObjectURL(url);
      });
  }
};

// 导出axios实例
export default service;
